package com.mankiw.tech.insight;

import java.util.ArrayList;
import java.util.List;

public class MyHashMap<K,V> {

    List<Node<K,V>> table = new ArrayList<Node<K,V>>();

    public V put(K key,V value){
        for(Node<K,V> node : table){
            if(node.key.equals(key)){
                var oldValue = node.value;
                node.value = value;
                return oldValue;
            }
        }
        Node<K,V> newNode = new Node<>(key,value);
        table.add(newNode);
        return null;
    }

    public V get(K key){
        for(Node<K,V> node : table){
            if(node.key.equals(key)){
                return node.value;
            }
        }
        return null;
    }

    public V remove(K key){
        //使用角标移除
        for (int i = 0; i < table.size(); i++) {
            Node<K,V> node = table.get(i);
            if(node.key.equals(key)){
                Node<K,V> removeNode = this.table.remove(i);
                return removeNode.value;
            }
        }
        return null;
    }

    //查询当前键值对个数
    public int size(){
        return this.table.size();
    }

    public class Node<K,V>{
        K key;
        V value;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }
}
